﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Web.Controllers
{
    
    using EC.Entity;
    using EC.Entity.Request.DepositOrder;
    using EC.Entity.Response.DepositOrder;
    using EC.Entity.Tables;

    public class HomeController : Controller
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public HomeController(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        public IActionResult Default()
        {
            return View();
        }

        /// <summary>
        /// 1000000?orderNo=QY100000&amount=200
        /// http://localhost:58457/home/index/1000000?orderNo=QY100000&amount=200
        /// </summary>
        /// <param name="id">商户</param>
        /// <param name="amount">金额</param>
        /// <param name="orderNo">订单号</param>
        /// <returns></returns>
        public IActionResult Index(int id, string orderNo = null,string amount=null)
        {
            var response = new JResult<CashResponse>()
            {
                Success = false
            };

            try
            {
                #region 验证
                if (string.IsNullOrEmpty(amount))
                {
                    throw new Exception("商户名称不能为空.");
                }

                var amountReg = new Regex(@"^(([1-9]\d{0,4})|0)?$");
                if (!amountReg.IsMatch(amount))
                {
                    throw new Exception("付款最大保留五位数");
                }
                #endregion


                //商户
                var merchants = _dbSession.DbConnection.Query<Merchant>("SELECT * FROM merchant WHERE Id=@Id", new { Id = id });

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("商户不存在.");
                }

                //获取银行卡
                var bankCards = _dbSession.DbConnection.Query<BankCard>("SELECT * FROM bankcard WHERE MerchantId=@MerchantId AND CardType=10 AND Frozen=1 AND Status=1 ORDER BY BalanceUpdateTime DESC", new { MerchantId = merchant.Id });

                var bankCard = bankCards.FirstOrDefault();
                if (bankCard == null)
                {
                    throw new Exception("无有效的银行卡.");
                }

                //存款订单
                var depositOrders = _dbSession.DbConnection.Query<DepositOrderResponse>("SELECT * FROM depositorder WHERE MerchantId=@MerchantId and MerchantOrderNo=@MerchantOrderNo", new { MerchantId = merchant.Id, MerchantOrderNo = orderNo });
                if (depositOrders != null && depositOrders.Any())
                {
                    var depositOrder = depositOrders.FirstOrDefault();
                    if (depositOrder != null)
                    {
                        var _bankCards = _dbSession.DbConnection.Query<BankCard>("SELECT * FROM bankcard WHERE Id=@Id", new { Id = depositOrder.DepositBankCardId });
                        if(_bankCards!=null && _bankCards.Any())
                        {
                            var _bankCard = _bankCards.FirstOrDefault();
                            if(_bankCard!=null)
                            {
                                response.Data = new CashResponse() {
                                    Order = depositOrder.MerchantOrderNo,
                                    BankName = _bankCard.BankName,
                                    BankCardNumber = _bankCard.BankCardNumber,
                                    BankCardName = _bankCard.BankCardName,
                                    Amount = depositOrder.PayAmount.ToString(),
                                };
                            }
                        }
                    }

                    response.Success = true;
                }
                else
                {
                    var milliseconds = $"0.{DateTime.Now.ToString("ss")}";

                    //订单金额
                    var depositAmount = Convert.ToDecimal(amount);
                    //支付金额
                    var payAmount = depositAmount - Convert.ToDecimal(milliseconds);
                    //利润
                    var lirunAmount = payAmount * merchant.DepositRate;
                    //结算
                    var jiesuanAmount = payAmount - lirunAmount;


                    var model = new DepositOrder();

                    model.MerchantId = merchant.Id;
                    model.MerchantOrderNo = orderNo;

                    model.DepositAmount = depositAmount;
                    model.PayAmount = payAmount;
                    model.JieSuanAmount = jiesuanAmount;
                    model.LiRunAmount = lirunAmount;

                    //model.DepositDate = null;
                    model.DepositBankCardId = bankCard.Id;
                    model.DepositCardNumber = bankCard.BankCardNumber;
                    //model.Transtype = null;

                    model.NoticeStatus = 1;
                    model.NoticeLastTime = null;
                    model.NoticeTimes = 0;

                    //model.NoticeInfo = null;
                    //model.Remark = null;
                    model.CreatedBy = 0;
                    model.CreatedDate = DateTime.Now;

                    ////新增
                    long resultId = _dbSession.DbConnection.Insert<DepositOrder>(model);

                    response.Data = new CashResponse()
                    {
                        Order = orderNo,
                        BankName = bankCard.BankName,
                        BankCardNumber = bankCard.BankCardNumber,
                        BankCardName = bankCard.BankCardName,
                        Amount = payAmount.ToString(),
                    };
                }

                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return View(response);
        }
    }
}
